// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';

// 视图插件
import {
  Empty,
  BackTop,
  Timeline,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

// css OR less预编译器
import styles from './NewsTracking.less';

// 图片

function timeConvert(e) {
  const date = new Date(e);
  const yy = `${date.getFullYear()}年`;
  const mm = `${date.getMonth() + 1}月`;
  const dd = `${date.getDate()}日 `;
  const h = `${date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()}:`;
  const m = `${date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()}:`;
  const s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
  return yy + mm + dd + h + m + s;
}
function timeConvert2(e) {
  const date = new Date(e);
  const yy = `${date.getFullYear()}.`;
  const mm = `${date.getMonth() + 1}.`;
  const dd = `${date.getDate()} `;
  const h = `${date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()}:`;
  const m = `${date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()}:`;
  const s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
  return yy + mm + dd + h + m + s;
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ newstracking, loading }) => ({
  newstracking,
  loading: loading.models.NewsTrackingRule,
}))
@Form.create()
class NewsTracking extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    isBottom: false, // 底部是否
    jitter: true, // 防抖动标志
    count: 20, // 总数
    lastTime: 0, // 最后一个time
    firstTime: 0, // 第一个time
    newCount: 0, // 新的新闻数
    newsFlag: 0, // 要问标志
    ifEmpty: false,
  };

  /**
   *  Describe:设置要闻
   *  Created by xjc on 2019/5/27
   */

  setNewsFlag(value) {
    const that = this;
    const { dispatch } = this.props;
    const { lastTime } = this.state;
    let flag = 0;

    clearInterval(this.dataBack);
    if (value.target.value === 'b') {
      flag = 1;
    }
    that.setState(
      {
        ifEmpty: true,
        newsFlag: flag,
      },
      () => {
        dispatch({
          type: 'newstracking/GetNews24List',
          payload: {
            count: 20,
            time: lastTime,
            flag,
          },
          callback: res => {
            if (res.code === 1) {
              if (res.data.length !== 0) {
                that.setState(
                  {
                    ifEmpty: false,
                    count: 20,
                    lastTime: res.data[res.data.length - 1].publishtime,
                    firstTime: res.data[0].publishtime,
                  },
                  () => {
                    that.contentNode.addEventListener('scroll', that.onScrollHandle.bind(this));
                    that.dataBack = setInterval(() => this.dataReload(), 6000);
                  }
                );
              }
            } else {
              message.error(res.message);
            }
          },
        });
      }
    );
  }

  /**
   *  Describe:滚动监听
   *  Created by xjc on 2019/5/23
   */

  onScrollHandle(event) {
    /*  message.config({
        top: 600,
        duration: 2,
        maxCount: 3,
      }); */
    const that = this;
    const { dispatch } = this.props;
    const { count, lastTime, jitter, newsFlag } = this.state;
    const { clientHeight } = event.target;
    const { scrollHeight } = event.target;
    const { scrollTop } = event.target;
    const isBottoms = clientHeight + scrollTop > scrollHeight - 5;
    if (isBottoms && jitter) {
      that.setState(
        {
          isBottom: true,
          count: count + 20,
          jitter: false,
        },
        () => {
          dispatch({
            type: 'newstracking/GetNews24ListAdd',
            payload: {
              count: 20,
              time: lastTime,
              flag: newsFlag,
            },
            callback: res => {
              if (res.code === 1) {
                if (res.data.length !== 0) {
                  that.setState({
                    isBottom: false,
                    lastTime: res.data[res.data.length - 1].publishtime,
                    jitter: true,
                  });
                }
              } else {
                that.setState({
                  jitter: true,
                });
                message.error(res.message);
              }
            },
          });
        }
      );
    }
  }

  /**
   *  Describe:自动刷
   *  Created by xjc on 2019/5/27
   */

  dataReload() {
    const that = this;
    const { dispatch } = this.props;
    const { count, firstTime, newsFlag } = this.state;
    dispatch({
      type: 'newstracking/GetNews24ListReloadCount',
      payload: {
        time: firstTime,
        flag: newsFlag,
      },
      callback: res => {
        if (res.code === 1) {
          that.setState(
            {
              newCount: res.data.count,
              count: count + res.data.count,
              flag: newsFlag,
            },
            () => {
              if (that.state.newCount !== 0) {
                dispatch({
                  type: 'newstracking/GetNews24ListReload',
                  payload: {
                    count: that.state.newCount,
                    time: firstTime,
                    flag: newsFlag,
                  },
                  callback: res => {
                    if (res.code === 1) {
                      if (that.state.newCount !== 0) {
                        that.setState({
                          firstTime: res.data[0].publishtime,
                        });
                        message.success(`您有新的${that.state.newCount}条数据已经加载`);
                      }
                    } else {
                      message.error(res.message);
                    }
                  },
                });
              }
            }
          );
        } else {
          message.error(res.message);
        }
      },
    });
  }

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const {
      newstracking: { newsData },
    } = this.props;
    const { isBottom, newsFlag, ifEmpty } = this.state;
    const TimelineData = newsData.data.map(item => {
      return (
        <Row>
          <Col
            sm={3}
            xs={6}
            style={{
              textAlign: 'center',
              top: '-5.6px',
              color: newsFlag === 0 && item.color === true ? '#f35d52' : '#444444',
            }}
          >
            {window.innerWidth > 414
              ? timeConvert(item.publishtime)
              : timeConvert2(item.publishtime)}
          </Col>
          <Col
            sm={18}
            xs={18}
            style={{ color: newsFlag === 0 && item.color === true ? '#f35d52' : '#444444' }}
          >
            <Timeline.Item>{item.content}</Timeline.Item>
          </Col>
        </Row>
      );
    });
    return (
      <PageHeaderWrapper title="新闻快讯">
        <Card bordered={false}>
          <div>
            <Radio.Group
              defaultValue="a"
              buttonStyle="solid"
              onChange={this.setNewsFlag.bind(this)}
            >
              <Radio.Button value="a">所有</Radio.Button>
              <Radio.Button value="b">只看要闻</Radio.Button>
            </Radio.Group>
          </div>
          <br />
          {ifEmpty ? (
            newsData.data.length === 0 ? (
              <div
                style={{
                  textAlign: 'center',
                  borderRadius: 4,
                  marginBottom: 20,
                  marginTop: 20,
                  padding: '30 50',
                  margin: '20 20',
                }}
              >
                {' '}
                <Spin size="large" />{' '}
              </div>
            ) : (
              <div
                style={{
                  textAlign: 'center',
                  borderRadius: 4,
                  marginBottom: 20,
                  marginTop: 20,
                  padding: '30 50',
                  margin: '20 20',
                }}
              >
                {' '}
                <Spin size="large" />{' '}
              </div>
            )
          ) : (
            <div
              id="pure"
              ref={node => (this.contentNode = node)}
              style={{ height: '866px', overflowY: 'scroll' }}
            >
              <Timeline>
                <br />
                {TimelineData}
              </Timeline>
              {isBottom ? (
                <div style={{ textAlign: 'center', borderRadius: '4px', padding: '30px' }}>
                  <Spin />
                </div>
              ) : null}
            </div>
          )}
        </Card>
        <BackTop visibilityHeight={100} />
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const that = this;

    /* 导入列表数据 */
    dispatch({
      type: 'newstracking/GetNews24List',
      payload: {},
      callback: res => {
        if (res.data.length !== 0) {
          that.contentNode.addEventListener('scroll', that.onScrollHandle.bind(this));
          that.setState({
            lastTime: res.data[res.data.length - 1].publishtime,
            firstTime: res.data[0].publishtime,
          });
        }
      },
    });

    this.dataBack = setInterval(() => this.dataReload(), 6000);
  }

  componentWillUnmount() {
    clearInterval(this.dataBack);
  }
}

export default NewsTracking;
